package croe.jdbc.mybatils;

import croe.jdbc.domain.ParameterThreadLocal;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.plugin.*;

import java.sql.PreparedStatement;
import java.util.Properties;

/**
 * User: zengzhili
 * Date: 14-8-1
 * Time: 下午5:30
 */
@Intercepts({@Signature(type = ParameterHandler.class, method = "setParameters", args = {PreparedStatement.class})})
public class ParameterHandlerPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        PreparedStatement preparedStatement = (PreparedStatement) invocation.getArgs()[0];
        Object[] parameters = ParameterThreadLocal.get();
        int count = 1;
        for (Object obj : parameters) {
            preparedStatement.setObject(count, obj);
            count++;
        }
        invocation.getArgs()[0] = preparedStatement;
        ParameterThreadLocal.remove();
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
